import {useState} from "react";
import {ICommonResponse, ISqlUpdate} from "@/global.ts";
import {message} from "antd";

const useTable = <T, K>(listApi: (params: K) => Promise<ICommonResponse<Array<T>>>, params: K) => {
    const [dataSource, setDataSource] = useState<Array<T>>([]);
    const [loading, setLoading] = useState(false);
    // 列表
    const getList = () => {
        setLoading(true)
        listApi(params).then(response => {
            if (response.code === 200) {
                setDataSource(response.data)
            }
        }).finally(() => {
            setLoading(false)
        })
    }
    // 删除
    const del = (api: (params: Array<string>) => Promise<ICommonResponse<ISqlUpdate>>, params: Array<string>, cb?: () => void): void => {
        api(params).then(response => {
            if (response.code === 200) {
                if (cb) cb()
                getList()
                message.success('删除成功')
            } else {
                message.error('删除失败')
            }
        })
    }

    return { loading, dataSource, getList, del }
}

export default useTable